package org.wx.io.netty.rpc.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.wx.io.netty.rpc.client.RpcClient;
import org.wx.io.netty.rpc.client.RpcClientInitializer;
import org.wx.io.netty.rpc.dispatcher.Dispatcher;
import org.wx.io.netty.rpc.intface.Car;
import org.wx.io.netty.rpc.intface.MyCar;

import java.net.InetSocketAddress;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: wangxun
 * @createDate: 2021/2/23
 * @version: 1.0
 */
@Slf4j
public class RpcServer implements Runnable{
    private InetSocketAddress inetSocketAddress;

    public RpcServer(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
    }

    @Override
    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new RpcServerInitializer());

            ChannelFuture bind = serverBootstrap.bind(inetSocketAddress);
            bind.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()){
                        log.info("服务器启动成功");
                        //初始化Dispatcher
                        Dispatcher.getDispatcher().register(Car.class.getName(),new MyCar());
                    }
                }
            });
            bind.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        // 利用自定义线程池去启动
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 10, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

        RpcServer rpcServer = new RpcServer(new InetSocketAddress("127.0.0.1", 8001));

        poolExecutor.execute(rpcServer);

    }
}
